package sort.test4_7;

import java.lang.reflect.Array;
import java.util.Arrays;

public class CountSort {
    public  int[]  countSort(int[] nums){
        if (nums.length==0){
            return null;
        }
        int length = nums.length;
        int max=Integer.MIN_VALUE;
        for (int i = 0; i < length ; i++) {
            if (max < nums[i]) {
                max = nums[i];
            }
        }
        //  CKG TODO 2023/4/7: 为什么是max+1  因为数组中还有0 这个元素值
        int[] countArray=new int[max+1];
        for (int i = 0; i < length; i++) {
            countArray[nums[i]]++;
        }

        for (int i = 1; i <countArray.length ; i++) {
            countArray[i]+=countArray[i-1];
        }

        int[] result = Arrays.copyOf(nums, length);

//        for (int i = 0; i < length; i++) {
//         nums[--countArray[result[i]]]=result[i];
//        }


        for (int i = nums.length-1; i>=0  ; i--) {
            nums[--countArray[result[i]]]=result[i];
        }

        return  nums;
    }

    public static void main(String[] args) {
        CountSort countSort = new CountSort();
        int arr[] ={3,44,38,5,47,15,36,26,27,2,46,4,19,50,48};
        countSort.countSort(arr);
        System.out.println(Arrays.toString(arr));
    }




}
